﻿using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.Linq;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;

namespace VisionCloud.Domain.Binder
{
    public class GuidModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext modelBinderProviderContext)
        {
            if (modelBinderProviderContext == null)
            {
                throw new ArgumentNullException(nameof(modelBinderProviderContext));
            }

            if (!modelBinderProviderContext.Metadata.IsComplexType)
            {
                try
                {
                    var propertyName = modelBinderProviderContext.Metadata.PropertyName;

                    var property = modelBinderProviderContext.Metadata.ContainerType.GetProperty(propertyName);

                    if (property != null)
                    {
                        var attribute = property.GetCustomAttributes(typeof(GuidAttribute), false).FirstOrDefault();

                        if (attribute != null)
                        {
                            return new GuidModelBinder(modelBinderProviderContext.Metadata.ModelType, attribute as IGuidAttribute);
                        }
                    }
                }
                catch (Exception exception)
                {
                    var message = exception.Message;

                    return null;
                }
            }

            return null;
        }
    }
}
